﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Text;
using Microsoft.ServiceBus;

namespace nwrole.lib {
    public class TcpRelayChannel<T> : IDisposable where T : IClientChannel {

        public T Channel { get; private set; }

        public TcpRelayChannel(string sbServiceNamespace, string sbServicePath, string sbIssuerName, string sbIssuerSecret) {
            Connect(sbServiceNamespace, sbServicePath, sbIssuerName, sbIssuerSecret);
        }


        private void Connect(string sbServiceNamespace, string sbServicePath, string sbIssuerName, string sbIssuerSecret)
        {
            ServiceBusEnvironment.SystemConnectivity.Mode = ConnectivityMode.AutoDetect;

            Uri serviceUri = ServiceBusEnvironment.CreateServiceUri("sb", sbServiceNamespace, sbServicePath);

            TransportClientEndpointBehavior sharedSecretServiceBusCredential = new TransportClientEndpointBehavior();
            sharedSecretServiceBusCredential.TokenProvider = TokenProvider.CreateSharedSecretTokenProvider(sbIssuerName, sbIssuerSecret);
            /*sharedSecretServiceBusCredential.CredentialType = TransportClientCredentialType.SharedSecret;
            sharedSecretServiceBusCredential.Credentials.SharedSecret.IssuerName = "owner";
            sharedSecretServiceBusCredential.Credentials.SharedSecret.IssuerSecret = "ihXdEKIJtg8jByN1aITLDX99eiEgMeHOfr4ppzX5MfM=";*/

            ChannelFactory<T> channelFactory = new ChannelFactory<T>();
            channelFactory.Endpoint.Address = new EndpointAddress(serviceUri);
            channelFactory.Endpoint.Binding = new NetTcpRelayBinding();
            channelFactory.Endpoint.Contract.ContractType = typeof(T);

            channelFactory.Endpoint.Behaviors.Add(sharedSecretServiceBusCredential);

            Channel = channelFactory.CreateChannel();
            Channel.Open();
        }

        public void Dispose() {
            try {
                Channel.Close(TimeSpan.FromSeconds(30));
                Channel.Dispose();
            } catch (Exception exception) {
                EventLogger.LogException("TcpRelayChannel.Dispose", exception);
            }
        }

    }
}
